package com.incross.dawin.util;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public abstract class BKTimer extends Handler {
	private static final int MESSAGE = 10000;
	
	private Context mContext;
	
	private boolean mIsTimerCancelled = false;
	private boolean mIsTimerStarted = false;
	
	private long mDelay = 0, mTempDelay = mDelay;
	private long mPeriod = 100, mTempPeriod = mPeriod;
	
	
	/**
	 * call this on scheduled time.
	 */
	protected abstract void doinOnTime();
	
	/**
	 * call this on timer in error.
	 */
	
	private OnTimerStateListener mTimerStateListener;
	
	protected abstract void onTimerError();
	
	public BKTimer() {
		
	}
	
	public interface OnTimerStateListener {
		public abstract void onTimerStarted();
		public abstract void onTimerCancelled();
	}
	
	
	
	/**
	 * start timer.
	 * @return : -1 if timer already started. 0 if success.
	 */
	public int start() {
		if(mIsTimerStarted) {
			return -1;
		} else {
			if(mTimerStateListener != null) {
				mTimerStateListener.onTimerStarted();
			}
			mIsTimerStarted = true;
			sendEmptyMessage(MESSAGE);
			return 0;
		}
	}
	
	
	/**
	 * sets delay for timer.
	 * @param delay : set delay millisecond.
	 */
	public void setDelay(long delay) {
		if(delay >= 0) {
			mDelay = delay;
			mTempDelay = mDelay;
		}
	}
	
	/**
	 * sets period for timer. default period 100 millisecond.
	 * @param period : set timer's period.
	 */
	public void setPeriod(long period) {
		if(period >= 0) {
			mPeriod = period;
			mTempPeriod = mPeriod;
		}
	}
	
	
	/**
	 * cancel timer.
	 * @return : 0 if cancelled success. -1 if timer is not started.
	 */
	public int cancel() {
		if(mIsTimerStarted) {
			mDelay = 1;
			mPeriod = 1;
			
			mIsTimerCancelled = true;
			this.removeMessages(MESSAGE);
			return 0;
		} else {
			return -1;
		}
	}
	
	@Override
	public void handleMessage(Message msg) {
		
		switch(msg.what) {
			case MESSAGE:
				if(!mIsTimerCancelled) {
					try {
						if(mDelay > 0) Thread.sleep(mDelay);
						doinOnTime();
						if(mPeriod > 0) Thread.sleep(mPeriod);
						sendEmptyMessage(MESSAGE);
					} catch (InterruptedException e) {
						e.printStackTrace();
						onTimerError();
					}
				} else {
					BKLog.i("Timer", "Timer cancelled");
					if(mTimerStateListener != null) {
						mTimerStateListener.onTimerCancelled();
					}
					
					mPeriod = mTempPeriod;
					mDelay = mTempDelay;
					
					mIsTimerStarted = false;
					mIsTimerCancelled = false;
				}
				
				break;
			
		}
		
		
	}
	
	
	
	
	
	
	
	

}
